#include <Wire.h>
#include <Sodaq_SHT2x.h>

#define BUTTON 8

#define COM1 A3
#define COM2 A2
#define COM3 A1
#define COM4 A0

#define SI_H  digitalWrite(10, HIGH)
#define SI_L  digitalWrite(10, LOW);
#define RCK_H digitalWrite(12, HIGH);
#define RCK_L digitalWrite(12, LOW);
#define SCK_H digitalWrite(13, HIGH);
#define SCK_L digitalWrite(13, LOW);
#define CS_H  digitalWrite(11, HIGH);
#define CS_L  digitalWrite(11, LOW); 
#define uchar unsigned char

int num[10] = { 
  159,130,91,211,198,213,221,131,223,215};
// 0 1 2 3 4 5 6 7 
// a b f e d h g c
// 0 0x9F
// 1 0x82
// 2 0x5B
// 3 0xD3
// 4 0xC6
// 5 0xD5
// 6 0xDD
// 7 0x83
// 8 0xDF
// 9 0xD7
void write_data(uchar data)
{
  uchar i;
  CS_H;
  for(i=0;i<8;i++)
  {
    if((data&0x80)==0x80)  SI_H;
    else                   SI_L;  
    SCK_H;
    delayMicroseconds(20);
    SCK_L;
    data=data<<1;  
  }
  RCK_L;
  delay(1);
  RCK_H;
  CS_L;
}

void displayAt(int place,int number,int point)
{
  selectC(place);
  write_data(num[number]|(place==point?B00100000:0));
}

void selectC(int com)
{
  switch(com) //选通位选
  {
  case 1:
    digitalWrite(COM1,LOW); //选择位1
    digitalWrite(COM2,HIGH);
    digitalWrite(COM3,HIGH);
    digitalWrite(COM4,HIGH);
    break;
  case 2:
    digitalWrite(COM1,HIGH);
    digitalWrite(COM2,LOW); //选择位2
    digitalWrite(COM3,HIGH);
    digitalWrite(COM4,HIGH);
    break;
  case 3:
    digitalWrite(COM1,HIGH);
    digitalWrite(COM2,HIGH);
    digitalWrite(COM3,LOW); //选择位3
    digitalWrite(COM4,HIGH);
    break;
  case 4:
    digitalWrite(COM1,HIGH);
    digitalWrite(COM2,HIGH);
    digitalWrite(COM3,HIGH);
    digitalWrite(COM4,LOW); //选择位4
    break;
  default:
    break;
  }
}
void clearS()
{
  for(int i=4;i>0;i--)
  {
    selectC(i);
    write_data(0);
  }
}

void setup ()
{
  pinMode(10, OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13,OUTPUT);

  pinMode(COM1, OUTPUT);
  pinMode(COM2, OUTPUT);
  pinMode(COM3, OUTPUT);
  pinMode(COM4, OUTPUT);

  Wire.begin();
}

unsigned long int now = 0;
void loop()
{
  clearS();
  int temp = SHT2x.GetTemperature() * 100;
  now = millis();
  while(millis()-now<=5000)
  {
    int dtemp = temp;

    if(digitalRead(BUTTON))
    {
      delay(50);
      if(digitalRead(BUTTON))
      {       
        clearS();
        int humidity = SHT2x.GetHumidity() * 10;
        while(digitalRead(BUTTON))
        {
          int dhumidity = humidity;
          for(int i=4;i>1;i--)
          {
            displayAt(i,dhumidity%10,3);
            dhumidity = dhumidity/10;
            delay(4);
          }
        }
        clearS();
      }
    }

    for(int i=4;i>0;i--)
    {
      displayAt(i,dtemp%10,2);
      dtemp = dtemp/10;
      delay(4);
    }
  }
}




